﻿using System.Globalization;
using System.Linq;
using System.Resources;
using System.Threading;

namespace Duellum.Core.ExceptionHelper
{
	internal sealed class SR
	{
		// Fields
		internal const string ArgumentArrayHasTooManyElements = "ArgumentArrayHasTooManyElements";
		internal const string ArgumentNotIEnumerableGeneric = "ArgumentNotIEnumerableGeneric";
		internal const string ArgumentNotLambda = "ArgumentNotLambda";
		internal const string ArgumentNotSequence = "ArgumentNotSequence";
		internal const string ArgumentNotValid = "ArgumentNotValid";
		internal const string EmptyEnumerable = "EmptyEnumerable";
		internal const string IncompatibleElementTypes = "IncompatibleElementTypes";
		private static SR loader;
		internal const string MoreThanOneElement = "MoreThanOneElement";
		internal const string MoreThanOneMatch = "MoreThanOneMatch";
		internal const string NoArgumentMatchingMethodsInQueryable = "NoArgumentMatchingMethodsInQueryable";
		internal const string NoElements = "NoElements";
		internal const string NoMatch = "NoMatch";
		internal const string NoMethodOnType = "NoMethodOnType";
		internal const string NoMethodOnTypeMatchingArguments = "NoMethodOnTypeMatchingArguments";
		internal const string NoNameMatchingMethodsInQueryable = "NoNameMatchingMethodsInQueryable";
		internal const string OwningTeam = "OwningTeam";
		private ResourceManager resources;

		// Methods
		internal SR()
		{
			this.resources = new ResourceManager("System.Linq", typeof(Enumerable).Assembly);
		}

		private static SR GetLoader()
		{
			if (loader == null) {
				SR sr = new SR();
				Interlocked.CompareExchange<SR>(ref loader, sr, null);
			}
			return loader;
		}

		static public object GetObject(string name)
		{
			SR loader = GetLoader();
			if (loader == null) return null;
			return loader.resources.GetObject(name, Culture);
		}

		static public string GetString(string name)
		{
			SR loader = GetLoader();
			if (loader == null) return null;
			return loader.resources.GetString(name, Culture);
		}

		static public string GetString(string name, params object[] args)
		{
			SR loader = GetLoader();
			if (loader == null) return null;
			string format = loader.resources.GetString(name, Culture);
			
			if ((args == null) || (args.Length <= 0)) return format;
			
			for (int i = 0; i < args.Length; i++) {
				string arg = args[i] as string;
				if ((arg != null) && (arg.Length > 0x400)) {
					args[i] = arg.Substring(0, 0x3fd) + "...";
				}
			}
			return string.Format(CultureInfo.CurrentCulture, format, args);
		}

		// Properties
		private static CultureInfo Culture
		{
			get { return null; }
		}

		static public ResourceManager Resources
		{
			get { return GetLoader().resources; }
		}
	}
}
